package com.example.baimao_tp.ui.screen

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.net.Uri
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.LifecycleOwner
import androidx.camera.core.Camera
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.Preview
import androidx.camera.core.TorchState
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.graphics.Brush
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import coil.compose.AsyncImage
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.ContextCompat
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage
import com.example.baimao_tp.data.ReferenceImage
import com.example.baimao_tp.viewmodel.CameraViewModel

@Composable
fun CameraScreen(
    viewModel: CameraViewModel = viewModel(),
    onBack: () -> Unit = {},
    onOpenSettings: () -> Unit = {}
) {
    val context = LocalContext.current
    val currentImage = viewModel.currentReferenceImage
    val canGoNext = viewModel.canGoNext()
    val canGoPrevious = viewModel.canGoPrevious()
    val isFlashOn = viewModel.isFlashOn
    val isLoading = viewModel.isLoading
    val errorMessage = viewModel.errorMessage

    Log.d("CameraScreen", "CameraScreen渲染中...")
    Log.d("CameraScreen", "当前状态: currentImage=${currentImage != null}, isLoading=$isLoading, errorMessage=$errorMessage")

    // 记录当前图片信息
    currentImage?.let { image ->
        Log.d("CameraScreen", "UI层当前图片信息: id=${image.id}, imageUrl=${image.imageUrl}, description=${image.description}")
    }

    // 在屏幕启动时自动加载数据（仅在首次启动且没有真实数据时）
    LaunchedEffect(Unit) {
        Log.d("CameraScreen", "CameraScreen启动，当前图片数量: ${viewModel.referenceImages.size}")
        Log.d("CameraScreen", "首次图片URL: ${viewModel.currentReferenceImage?.imageUrl}")
        Log.d("CameraScreen", "当前语言设置: ${viewModel.selectedLanguage}")

        // 延迟一段时间，确保MainActivity的语言设置完成
        kotlinx.coroutines.delay(200)

        // 检查是否需要显示引导界面（在语言设置完成后）
        viewModel.checkAndShowGuide(context)

        // 再次延迟，确保引导界面状态更新完成
        kotlinx.coroutines.delay(100)

        // 只有在没有真实图片数据时才加载初始数据（避免覆盖筛选条件）
        val hasRealImages = viewModel.referenceImages.isNotEmpty() &&
                          !viewModel.currentReferenceImage?.imageUrl.isNullOrBlank()

        if (!hasRealImages) {
            Log.d("CameraScreen", "没有真实图片数据，开始获取服务器数据...")
            viewModel.fetchReferenceImagesFromServer()
        } else {
            Log.d("CameraScreen", "已有真实图片数据，跳过初始加载以保持筛选条件")
        }

        // 测试系统语言检测
        viewModel.testSystemLanguageDetection(context)
    }

    // 监听数据变化
    LaunchedEffect(currentImage) {
        Log.d("CameraScreen", "当前图片发生变化: ${currentImage?.id}")
    }

    // 监听加载状态变化
    LaunchedEffect(isLoading) {
        Log.d("CameraScreen", "加载状态变化: $isLoading")
    }

    // 显示错误提示
    errorMessage?.let { message ->
        LaunchedEffect(message) {
            Log.e("CameraScreen", "收到错误消息: $message")

            // 显示Toast提示
            Toast.makeText(context, message, Toast.LENGTH_LONG).show()

            // 延迟清除错误消息
            kotlinx.coroutines.delay(5000)
            viewModel.clearErrorMessage()
        }
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Black)
    ) {
        // Full screen camera preview
        CameraPreview(
            isFlashOn = isFlashOn,
            viewModel = viewModel
        )

        // 引导界面覆盖层
        if (viewModel.showGuide) {
            GuideOverlay(
                viewModel = viewModel,
                onGuideComplete = {
                    // 引导完成后的回调，可以在这里执行额外逻辑
                    Log.d("CameraScreen", "引导界面完成")
                }
            )
        }

        // Image expanded overlay
        if (viewModel.isImageExpanded && currentImage != null) {
            ImageExpandedOverlay(
                referenceImage = currentImage,
                currentImageIndex = viewModel.currentImageIndex,
                referenceImages = viewModel.referenceImages,
                onClose = { viewModel.closeImageExpanded() },
                onNext = {
                    viewModel.nextImage()
                },
                onPrevious = {
                    viewModel.previousImage()
                },
                canGoNext = canGoNext,
                canGoPrevious = canGoPrevious
            )
        }

        // Captured images overlay
        if (viewModel.showCapturedImages) {
            CapturedImagesOverlay(
                capturedImages = viewModel.capturedImages,
                onClose = { viewModel.closeCapturedImages() }
            )
        }

        // Top control bar floating on top
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .align(Alignment.TopCenter)
                .background(
                    brush = Brush.verticalGradient(
                        colors = listOf(
                            Color(0x60FFFFFF),
                            Color(0x20FFFFFF),
                            Color.Transparent
                        ),
                        startY = 0f,
                        endY = Float.POSITIVE_INFINITY
                    )
                )
        ) {
            TopControlBar(
            onBack = onBack,
            onExitApp = {
                // Exit the app
                System.exit(0)
            },
            isFlashOn = isFlashOn,
            onToggleFlash = viewModel::toggleFlash,
            onOpenSettings = onOpenSettings
        )
        }

        // Bottom control section floating on top
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .align(Alignment.BottomCenter)
                .background(
                    brush = Brush.verticalGradient(
                        colors = listOf(
                            Color.Transparent,
                            Color(0x20FFFFFF),
                            Color(0x60FFFFFF)
                        ),
                        startY = 0f,
                        endY = Float.POSITIVE_INFINITY
                    )
                )
        ) {
            BottomControlSection(
                context = context,
                viewModel = viewModel,
                currentImage = currentImage,
                onPreviousImage = viewModel::previousImage,
                onNextImage = viewModel::nextImage,
                onImageClick = viewModel::toggleImageExpanded,
                canGoPrevious = canGoPrevious,
                canGoNext = canGoNext
            )
        }
    }
}

@Composable
private fun TopControlBar(
    onBack: () -> Unit,
    onExitApp: () -> Unit = {},
    isFlashOn: Boolean = false,
    onToggleFlash: () -> Unit = {},
    onOpenSettings: () -> Unit = {}
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 32.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        // Left - Exit app button
        Box(
            modifier = Modifier
                .size(40.dp)
                .clip(CircleShape)
                .background(Color(0x40FFFFFF))
                .clickable { onExitApp() },
            contentAlignment = Alignment.Center
        ) {
            Text("✖", color = Color.White, fontSize = 20.sp)
        }

        // Right - Function buttons
        Row(
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // Flash/Light button
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .clip(CircleShape)
                    .background(
                        if (isFlashOn) Color(0xFFFFA500) else Color(0x40FFFFFF)
                    )
                    .clickable { onToggleFlash() },
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = "⚡",
                    color = if (isFlashOn) Color.Black else Color.White,
                    fontSize = 20.sp
                )
            }

            // Settings button (moved from left)
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .clip(CircleShape)
                    .background(Color(0x40FFFFFF))
                    .clickable { onOpenSettings() },
                contentAlignment = Alignment.Center
            ) {
                Text("⚙", color = Color.White, fontSize = 20.sp)
            }
        }
    }
}

@Composable
private fun ReferenceImageThumbnail(
    referenceImage: ReferenceImage,
    modifier: Modifier = Modifier
) {
    Box(
        modifier = modifier
            .size(80.dp)
            .clip(RoundedCornerShape(8.dp))
            .background(Color.Gray),
        contentAlignment = Alignment.Center
    ) {
        // Placeholder for reference image
        Text(
            text = "Ref",
            color = Color.White,
            fontSize = 12.sp
        )
    }
}

@Composable
private fun BottomControlSection(
    context: Context,
    viewModel: CameraViewModel,
    currentImage: ReferenceImage?,
    onPreviousImage: () -> Unit,
    onNextImage: () -> Unit,
    onImageClick: () -> Unit = {},
    canGoPrevious: Boolean = true,
    canGoNext: Boolean = true
) {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(130.dp)
            .padding(vertical = 20.dp, horizontal = 16.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .align(Alignment.Center),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            // Left - Reference image thumbnail with navigation hints
            if (currentImage != null) {
                Log.d("CameraScreen", "渲染Ref区域 - 图片URL: ${currentImage.imageUrl}")

                // Add a subtle pulsing animation to draw attention
                val scaleAnimation = remember { androidx.compose.animation.core.Animatable(1f) }
                LaunchedEffect(Unit) {
                    // Only pulse for the first few seconds to draw attention
                    kotlinx.coroutines.delay(2000) // Wait 2 seconds before starting
                    repeat(3) {
                        scaleAnimation.animateTo(
                            targetValue = 1.05f,
                            animationSpec = androidx.compose.animation.core.tween(
                                durationMillis = 800,
                                easing = androidx.compose.animation.core.EaseInOutCubic
                            )
                        )
                        scaleAnimation.animateTo(
                            targetValue = 1f,
                            animationSpec = androidx.compose.animation.core.tween(
                                durationMillis = 800,
                                easing = androidx.compose.animation.core.EaseInOutCubic
                            )
                        )
                    }
                }

                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.Center
                ) {
                    // Main thumbnail
                    Box(
                        modifier = Modifier
                            .size(width = 70.dp, height = 70.dp)
                            .scale(scaleAnimation.value)
                            .clip(RoundedCornerShape(8.dp))
                            .background(Color(0x40FFFFFF))
                            .clickable {
                                Log.d("CameraScreen", "Ref区域被点击，放大展示图片")
                                onImageClick()
                            },
                        contentAlignment = Alignment.Center
                    ) {
                        AsyncImage(
                            model = currentImage.imageUrl,
                            contentDescription = currentImage.description,
                            modifier = Modifier
                                .fillMaxSize()
                                .clip(RoundedCornerShape(8.dp)),
                            contentScale = androidx.compose.ui.layout.ContentScale.Crop,
                            placeholder = null,
                            error = null,
                            fallback = null,
                            onLoading = { state ->
                                Log.d("CameraScreen", "AsyncImage开始加载: ${currentImage.imageUrl}")
                            },
                            onSuccess = { state ->
                                Log.d("CameraScreen", "AsyncImage加载成功: ${currentImage.imageUrl}")
                            },
                            onError = { state ->
                                Log.e("CameraScreen", "AsyncImage加载失败: ${currentImage.imageUrl} - Error: ${state.result.throwable?.message}")
                            }
                        )

                      }

                  }
            } else {
                Spacer(modifier = Modifier.size(width = 70.dp, height = 90.dp))
            }

            // Center - Large capture button
            CaptureButton(
                onCapture = {
                    viewModel.capturePhoto(context) { capturedPath ->
                        if (capturedPath != null) {
                            Toast.makeText(context, "拍照成功", Toast.LENGTH_SHORT).show()
                        } else {
                            Toast.makeText(context, "拍照失败", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            )

            // Right - Latest captured image thumbnail or gallery button
            Box(
                modifier = Modifier
                    .size(width = 70.dp, height = 90.dp)
                    .clip(RoundedCornerShape(8.dp))
                    .background(Color(0x40FFFFFF))
                    .clickable {
                        viewModel.toggleCapturedImages()
                    },
                contentAlignment = Alignment.Center
            ) {
                // 如果有拍摄的照片，显示最新的缩略图
                if (viewModel.capturedImages.isNotEmpty()) {
                    val latestImagePath = viewModel.capturedImages.first()

                    // 判断是URI还是文件路径
                    val imageUri = if (latestImagePath.startsWith("content://") || latestImagePath.startsWith("file://")) {
                        Uri.parse(latestImagePath)
                    } else {
                        Uri.fromFile(java.io.File(latestImagePath))
                    }

                    Box(
                        modifier = Modifier.fillMaxSize()
                    ) {
                        AsyncImage(
                            model = imageUri,
                            contentDescription = "Latest captured photo",
                            modifier = Modifier
                                .fillMaxSize()
                                .clip(RoundedCornerShape(8.dp)),
                            contentScale = androidx.compose.ui.layout.ContentScale.Crop,
                            onError = { error ->
                                Log.e("CameraScreen", "右下角缩略图加载失败: ${error.result.throwable?.message}")
                            }
                        )

                        // 添加一个半透明的边框表示这是最新拍摄的照片
                        Box(
                            modifier = Modifier
                                .fillMaxSize()
                                .clip(RoundedCornerShape(8.dp))
                                .background(
                                    Brush.verticalGradient(
                                        colors = listOf(
                                            Color.Transparent,
                                            Color(0x15FF0000) // 半透明红色渐变，更淡一些
                                        )
                                    )
                                )
                        )

                        // 添加一个小圆点表示这是最新拍摄的照片
                        Box(
                            modifier = Modifier
                                .align(Alignment.TopEnd)
                                .offset(x = (-2).dp, y = 2.dp)
                                .size(8.dp)
                                .clip(CircleShape)
                                .background(Color.Red)
                        )
                    }
                } else {
                    // 没有拍摄照片时显示默认图标
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.Center,
                        modifier = Modifier.fillMaxSize()
                    ) {
                        Text("🎬", fontSize = 24.sp)
                        Text("Gallery", color = Color.Black, fontSize = 10.sp)
                    }
                }
            }
        }
    }
}

@Composable
private fun CameraPreview(
    isFlashOn: Boolean = false,
    viewModel: CameraViewModel
) {
    val context = LocalContext.current
    val lifecycleOwner = LocalLifecycleOwner.current

    // 检查相机权限
    if (ContextCompat.checkSelfPermission(
            context,
            Manifest.permission.CAMERA
        ) != PackageManager.PERMISSION_GRANTED
    ) {
        Text(
            text = "需要相机权限",
            color = Color.White,
            fontSize = 16.sp
        )
        return
    }

    AndroidView(
        factory = { ctx ->
            val previewView = PreviewView(ctx).apply {
                // 设置预览模式，减少缓冲区问题
                implementationMode = PreviewView.ImplementationMode.COMPATIBLE
                scaleType = PreviewView.ScaleType.FILL_CENTER
            }
            val executor = ContextCompat.getMainExecutor(ctx)
            var camera: Camera? = null

            val cameraProviderFuture = ProcessCameraProvider.getInstance(ctx)
            cameraProviderFuture.addListener({
                setupCamera(previewView, ctx, lifecycleOwner, viewModel)
            }, executor)

            previewView
        },
        update = { view ->
            // 当isFlashOn状态变化时，更新闪光灯状态
            updateFlashLight(view, lifecycleOwner, viewModel, isFlashOn)
        },
        modifier = Modifier.fillMaxSize()
    )
}

// 相机设置函数
private fun setupCamera(
    previewView: PreviewView,
    context: Context,
    lifecycleOwner: LifecycleOwner,
    viewModel: CameraViewModel
) {
    try {
        val cameraProvider = ProcessCameraProvider.getInstance(context).get()

        val preview = Preview.Builder()
            .setTargetAspectRatio(androidx.camera.core.AspectRatio.RATIO_16_9)
            .build()
            .also {
                it.setSurfaceProvider(previewView.surfaceProvider)
            }

        val imageCapture = ImageCapture.Builder()
            .setTargetAspectRatio(androidx.camera.core.AspectRatio.RATIO_16_9)
            .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
            .build()

        // 传递ImageCapture给ViewModel
        viewModel.imageCapture = imageCapture

        val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA

        try {
            cameraProvider.unbindAll()
            cameraProvider.bindToLifecycle(
                lifecycleOwner,
                cameraSelector,
                preview,
                imageCapture
            )
        } catch (exc: Exception) {
            Log.e("CameraScreen", "相机绑定失败", exc)
        }
    } catch (exc: Exception) {
        Log.e("CameraScreen", "获取相机提供者失败", exc)
    }
}

// 闪光灯更新函数
private fun updateFlashLight(
    view: android.view.View,
    lifecycleOwner: LifecycleOwner,
    viewModel: CameraViewModel,
    isFlashOn: Boolean
) {
    try {
        val cameraProvider = ProcessCameraProvider.getInstance(view.context).get()
        cameraProvider.unbindAll()

        val preview = Preview.Builder()
            .setTargetAspectRatio(androidx.camera.core.AspectRatio.RATIO_16_9)
            .build()
            .also {
                it.setSurfaceProvider((view as PreviewView).surfaceProvider)
            }

        val imageCapture = ImageCapture.Builder()
            .setTargetAspectRatio(androidx.camera.core.AspectRatio.RATIO_16_9)
            .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
            .build()

        // 更新ViewModel中的ImageCapture实例
        viewModel.imageCapture = imageCapture

        val camera = cameraProvider.bindToLifecycle(
            lifecycleOwner,
            CameraSelector.DEFAULT_BACK_CAMERA,
            preview,
            imageCapture
        )
        camera.cameraControl.enableTorch(isFlashOn)
    } catch (exc: Exception) {
        Log.e("CameraScreen", "闪光灯控制失败", exc)
    }
}

@Composable
private fun ImageExpandedOverlay(
    referenceImage: ReferenceImage,
    currentImageIndex: Int,
    referenceImages: List<ReferenceImage>,
    onClose: () -> Unit,
    onNext: () -> Unit = {},
    onPrevious: () -> Unit = {},
    canGoNext: Boolean = true,
    canGoPrevious: Boolean = true
) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color(0xCC000000)) // Semi-transparent black background
            .clickable { onClose() }, // Close when clicking outside
        contentAlignment = Alignment.Center
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center,
            modifier = Modifier
                .fillMaxWidth(0.9f)
                .clickable { /* Prevent closing when clicking on content */ }
        ) {
            // Close button in top right corner
            Box(
                modifier = Modifier
                    .align(Alignment.End)
                    .padding(16.dp)
                    .size(32.dp)
                    .clip(CircleShape)
                    .background(Color(0x40FFFFFF))
                    .clickable { onClose() },
                contentAlignment = Alignment.Center
            ) {
                Text("✖", color = Color.White, fontSize = 18.sp)
            }

            Spacer(modifier = Modifier.height(16.dp))

            // Expanded image with navigation arrows
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(400.dp)
                    .clip(RoundedCornerShape(12.dp))
                    .background(Color.Gray)
                    .pointerInput(canGoNext, canGoPrevious) {
                        var totalDragX = 0f
                        detectDragGestures(
                            onDragEnd = {
                                val threshold = 300f // 滑动阈值

                                when {
                                    // 右滑 - 上一张图片
                                    totalDragX > threshold && canGoPrevious -> {
                                        onPrevious()
                                    }
                                    // 左滑 - 下一张图片
                                    totalDragX < -threshold && canGoNext -> {
                                        onNext()
                                    }
                                }
                                totalDragX = 0f // 重置累计滑动距离
                            }
                        ) { change, dragAmount ->
                            totalDragX += dragAmount.x
                        }
                    },
                contentAlignment = Alignment.Center
            ) {
                // Main image
                AsyncImage(
                    model = referenceImage.imageUrl,
                    contentDescription = referenceImage.description,
                    modifier = Modifier
                        .fillMaxSize()
                        .clip(RoundedCornerShape(12.dp)),
                    contentScale = androidx.compose.ui.layout.ContentScale.Fit,
                    placeholder = null,
                    error = null,
                    fallback = null
                )

                // Left arrow (previous image)
                if (canGoPrevious) {
                    Box(
                        modifier = Modifier
                            .align(Alignment.CenterStart)
                            .padding(start = 8.dp, end = 16.dp, top = 16.dp, bottom = 16.dp)
                            .size(40.dp)
                            .clip(CircleShape)
                            .background(Color(0x90000000)) // More opaque for better visibility
                            .clickable {
                                Log.d("ImageExpandedOverlay", "左箭头被点击")
                                onPrevious()
                            },
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = "❮",
                            color = Color.White,
                            fontSize = 20.sp,
                            fontWeight = androidx.compose.ui.text.font.FontWeight.Bold
                        )
                    }
                }

                // Right arrow (next image)
                if (canGoNext) {
                    Box(
                        modifier = Modifier
                            .align(Alignment.CenterEnd)
                            .padding(start = 16.dp, end = 8.dp, top = 16.dp, bottom = 16.dp)
                            .size(40.dp)
                            .clip(CircleShape)
                            .background(Color(0x90000000)) // More opaque for better visibility
                            .clickable {
                                Log.d("ImageExpandedOverlay", "右箭头被点击")
                                onNext()
                            },
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = "❯",
                            color = Color.White,
                            fontSize = 20.sp,
                            fontWeight = androidx.compose.ui.text.font.FontWeight.Bold
                        )
                    }
                }
            }

            Spacer(modifier = Modifier.height(16.dp))

            // Image description
            Text(
                text = referenceImage.description ?: "No description",
                color = Color.White,
                fontSize = 16.sp,
                textAlign = androidx.compose.ui.text.style.TextAlign.Center,
                modifier = Modifier.padding(horizontal = 16.dp)
            )

            Spacer(modifier = Modifier.height(40.dp))
        }
    }
}

@Composable
private fun CaptureButton(
    onCapture: () -> Unit = {}
) {
    val scale = remember { mutableStateOf(1f) }

    Box(
        modifier = Modifier
            .size(80.dp)
            .scale(scale.value)
            .clip(CircleShape)
            .background(Color.White)
            .clickable {
                scale.value = 0.9f
                onCapture()
                // 动画效果：按下缩小，松开还原
                GlobalScope.launch {
                    kotlinx.coroutines.delay(100)
                    scale.value = 1f
                }
            },
        contentAlignment = Alignment.Center
    ) {
        // Outer white ring
        Box(
            modifier = Modifier
                .size(80.dp)
                .clip(CircleShape)
                .background(Color.White)
        ) {
            // Inner solid circle
            Box(
                modifier = Modifier
                    .size(60.dp)
                    .clip(CircleShape)
                    .background(Color.Red)
                    .align(Alignment.Center)
            )
        }
    }
}

@Composable
private fun CapturedImagesOverlay(
    capturedImages: List<String>,
    onClose: () -> Unit
) {
    val currentImageIndex = remember { mutableStateOf(0) }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color(0xCC000000))
            .clickable { onClose() },
        contentAlignment = Alignment.Center
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center,
            modifier = Modifier
                .fillMaxWidth(0.9f)
                .clickable { /* Prevent closing when clicking on content */ }
        ) {
            // Close button in top right corner
            Box(
                modifier = Modifier
                    .align(Alignment.End)
                    .padding(16.dp)
                    .size(32.dp)
                    .clip(CircleShape)
                    .background(Color(0x40FFFFFF))
                    .clickable { onClose() },
                contentAlignment = Alignment.Center
            ) {
                Text("✖", color = Color.White, fontSize = 18.sp)
            }

            Spacer(modifier = Modifier.height(16.dp))

            if (capturedImages.isNotEmpty()) {
                // Current captured image
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(400.dp)
                        .clip(RoundedCornerShape(12.dp))
                        .background(Color.Gray)
                        .pointerInput(Unit) {
                            var totalDragX = 0f
                            detectDragGestures(
                                onDragEnd = {
                                    val threshold = 300f

                                    when {
                                        // 右滑 - 上一张图片
                                        totalDragX > threshold && currentImageIndex.value > 0 -> {
                                            currentImageIndex.value--
                                        }
                                        // 左滑 - 下一张图片
                                        totalDragX < -threshold && currentImageIndex.value < capturedImages.size - 1 -> {
                                            currentImageIndex.value++
                                        }
                                    }
                                    totalDragX = 0f
                                }
                            ) { change, dragAmount ->
                                totalDragX += dragAmount.x
                            }
                        },
                    contentAlignment = Alignment.Center
                ) {
                    val currentImagePath = capturedImages[currentImageIndex.value]

                    // 判断是URI还是文件路径
                    val imageUri = if (currentImagePath.startsWith("content://") || currentImagePath.startsWith("file://")) {
                        Uri.parse(currentImagePath)
                    } else {
                        Uri.fromFile(java.io.File(currentImagePath))
                    }

                    AsyncImage(
                        model = imageUri,
                        contentDescription = "Captured photo ${currentImageIndex.value + 1}",
                        modifier = Modifier.fillMaxSize(),
                        contentScale = androidx.compose.ui.layout.ContentScale.Fit,
                        onError = { error ->
                            Log.e("CameraScreen", "图片加载失败: ${error.result.throwable}")
                        }
                    )
                }

                Spacer(modifier = Modifier.height(16.dp))

                // Image counter
                Text(
                    text = "${currentImageIndex.value + 1} / ${capturedImages.size}",
                    color = Color.White,
                    fontSize = 14.sp
                )
            } else {
                // No images captured
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(300.dp)
                        .clip(RoundedCornerShape(12.dp))
                        .background(Color(0x40FFFFFF)),
                    contentAlignment = Alignment.Center
                ) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Text("📷", color = Color.White, fontSize = 48.sp)
                        Spacer(modifier = Modifier.height(16.dp))
                        Text(
                            text = "还没有拍摄任何照片",
                            color = Color.White,
                            fontSize = 16.sp
                        )
                    }
                }
            }

            Spacer(modifier = Modifier.height(40.dp))
        }
    }
}

@Composable
fun CameraScreenPreview() {
    CameraScreen()
}
